var provinces=[];
$(window).load(function() {

	//设置表单样式
	setFormCSS();
});

//将表单数据序列化为json对象
(function($){
  $.fn.serializeJson=function(){
      var serializeObj={};
      var array=this.serializeArray();
      var str=this.serialize();
      $(array).each(function(){
          if(serializeObj[this.name]){
              if($.isArray(serializeObj[this.name])){
                  serializeObj[this.name].push(this.value);
              }else{
                  serializeObj[this.name]=[serializeObj[this.name],this.value];
              }
          }else{
              serializeObj[this.name]=this.value; 
          }
      });
      return serializeObj;
  };
})(jQuery);

$(function() {
	//获取省列表
	$.ajax({
		url: PROJECT_NAME + '/province_list.do',
		type: 'POST',
		dataType: "json",
		success: function(data, status) {
			provinces=data;
			var d=new Array();
			d.push({ "text": "请选择","value": 0,"selected":true});
			$.each(data,function(index,value){
				d.push({ "text": value.name,"value": value.id});
			});
			//省列表
			$('#province').combobox({
				valueField: 'value',
				textField: 'text',
				data:d,
				onChange:function(newValue, oldValue){
					if (newValue>0) {
						$.each(provinces, function(index, value) {
							if (newValue==value.id) {
								if (!value.cities) {
									$.ajax({
										url: PROJECT_NAME + '/city_list.do',
										type: 'POST',
										data:{provinceId:newValue},
										dataType: "json",
										success: function(data, status) {
											value.cities=data;
											var cd=new Array();
											cd.push({ "text": "请选择","value": 0,"selected":true});
											$.each(value.cities,function(i,v){
												cd.push({ "text": v.name,"value": v.id});
											});
											$('#city').combobox('loadData',cd);
										},
										err: function(XMLHttpRequest, textStatus, err) {
											$.messager.alert('错误', '对不起，获取城市列表失败！', 'error');
										}
									});
								}else{
									var cd=new Array();
									cd.push({ "text": "请选择","value": 0,"selected":true});
									$.each(value.cities,function(i,v){
										cd.push({ "text": v.name,"value": v.id});
									});
									$('#city').combobox('loadData',cd);
								}
								
								return false;
							}
						});
					}else{
						$('#city').combobox('loadData',[{ "text": "请选择","value": 0,"selected":true}]);
					}
				}
			});
			
		},
		err: function(XMLHttpRequest, textStatus, err) {
			$.messager.alert('错误', '对不起，获取省市列表失败！', 'error');
		}
	});
	
	$('#city').combobox({
		valueField: 'value',
		textField: 'text',
		data: [{ "text": "请选择","value": 0,"selected":true}]
	});
	
	//为id为query的按钮添加单击事件，让id为dg的DataGrid从服务器重新加载数据，常用于查询
	$("#querybtn").click(function() {
		$("#userGrid").datagrid('load', {
			//此处填写提交给服务器的参数，为JSON数据格式，可以添加多个参数
			"uname": $("#uname").val(),
			"userinfo.name": $("#name").val(),
			"status": $("#status").combobox('getValue'),
			"userinfo.sex": $("#sex").combobox('getValue'),
			"role.id": $("#role").combobox('getValue'),
		});

	});
	$("#addbtn").click(function() {
		$("#pwdtr").show(0);
		$("#repwdtr").hide(0);
		
		$("#dlg .easyui-textbox").textbox({    
			readonly:false
		});
		$("#dlg .easyui-combobox").textbox({    
			readonly:false
		});
		$("#dlg .easyui-datebox").textbox({    
			readonly:false
		});
		$('#dlg').dialog({
			title: '添加用户',
			height:275,
			iconCls: 'icon-add',
			onResize:function(width,height){
				$("#dlg .easyui-textbox,#dlg .easyui-combobox,#dlg .easyui-datebox").each(function(idx,dom){
					$(this).textbox({    
						width:$(this).parent().width()-15
					});
				});
			},
			buttons:[{
				text:'确定',
				iconCls: 'icon-ok',
				handler:function(){
						submitForm({
				    		url:PROJECT_NAME + '/user_saveorupdate.do',
				    		msg:"添加成功",
				    		action:"add",
				    		reload:false,
				    		append:true,
				    		row:$('#fm').serializeJson()
				    	});
				}
			},{
				text:'关闭',
				iconCls: 'icon-cancel',
				handler:function(){
					$('#dlg').dialog('close');
				}
			}]
		});
		var roles=$("#dlgrole").combobox('getData');
		$("#dlgrole").combobox('select',roles[0].value);
		var pro=$("#province").combobox('getData');
		$("#province").combobox('select',pro[0].value);
		var cities=$("#city").combobox('getData');
		$("#city").combobox('select',cities[0].value);
		$("#dlgsex").combobox('select','保密');
		
		$("#birthday").datebox('clear');
		
		$("#dlg .easyui-textbox").textbox('clear');
		$("#dlgstatus").val(1);
		$("#userId").val(0);
		$('#dlg').dialog('open');
		
	});
	$("#activebtn").click(function() {
		updateUsersStatus("审核","active");
	});
	
	$("#lockbtn").click(function() {
		updateUsersStatus("封停","lock");
	});
	$("#unloackbtn").click(function() {
		updateUsersStatus("解封","unlock");
	});


	$.ajax({
		url: PROJECT_NAME + '/role_list.do',
		type: 'POST',
		dataType: "json",
		success: function(data, status) {
			var d=new Array();
			d.push({ "text": "不限","value": 0,"selected":true});
			$.each(data,function(index,value){
				d.push(value);
			});
			$('#role').combobox({
				panelHeight: 'auto',
				valueField: 'value',
				textField: 'text',
				data: d
			});
			data[0].selected=true;
			$('#dlgrole').combobox({
				panelHeight: 'auto',
				valueField: 'value',
				textField: 'text',
				data: data
			});
		},
		err: function(XMLHttpRequest, textStatus, err) {
			$.messager.alert('错误', '对不起，获取角色列表失败！', 'error');
		}
	});

	initDataGrid(
		"#userGrid",
		PROJECT_NAME + '/user_query.do', {
			"status": -1,
			"role.id":0
		},
		'#toolbar',
		'id', [
			[{
					field: 'id',
					title: 'ID',
					hidden: true
				},{
					field: 'ck',
					checkbox: true
				}, {
					field: 'roleId',
					title: '角色',
					hidden: true
				},
				{
					field: 'uname',
					title: "用户名",
					align: 'center',
					width: 10
				}, {
					field: 'name',
					title: "姓名",
					align: 'center',
					width: 5
				}, {
					field: 'sex',
					title: "性别",
					align: 'center',
					width: 5
				}, {
					field: 'birthday',
					title: "生日",
					align: 'center',
					width: 8
				}, {
					field: 'provinceId',
					title: "省",
					hidden: true
				}, {
					field: 'cityId',
					title: '市',
					hidden: true
				}, {
					field: 'tel',
					title: '固定电话',
					hidden: true
				}, {
					field: 'mobile',
					title: '手机',
					align: 'center',
					width: 10,
				}, {
					field: 'address',
					title: '地址',
					hidden: true
				}, {
					field: 'qq',
					title: 'QQ',
					align: 'center',
					width: 10,
				}, {
					field: 'weChat',
					title: '微信',
					align: 'center',
					width: 10,
				}, {
					field: 'email',
					title: '邮箱',
					align: 'center',
					width: 20,
				}, {
					field: 'roleName',
					title: '用户角色',
					align: 'center',
					width: 8,
				}, {
					field: 'status',
					title: "账户状态",
					align: 'center',
					width: 5,
					formatter: function(value, row, index) {
						if(value == 1) {
							return "正常";
						} else if(value == 0) {
							return "停封";
						} else if(value == 2) {
							return "待审核";
						} else {
							return "未知";
						}
					},
					styler: function(value, row, index) {
						if(value == 1) {
							return 'color:green;';
						} else if(value == 0) {
							return 'color:red;';
						} else if(value == 2) {
							return 'color:blue;';
						} else {
							return 'color:yellow;';
						}
					}
				}, {
					field: 'opt',
					title: "操  作",
					align: 'center',
					width: 10,
					//设置按钮列
					formatter: function(value, row, index) {
						var e = '<a  class="editcls" onclick="editUser(' + index + ')"></a> ';
						var s = '<a  class="showcls" onclick="showUser(' + index + ')"></a>';
						var d = '<a  class="nocls" onclick="lockUser(' + index + ')"></a>';
						var o =  '<a  class="okcls" onclick="unlockUser(' + index + ',\'您确认解封吗？\',\'解封成功\')"></a>';
						var a = '<a  class="tipcls" onclick="unlockUser(' + index + ',\'您确认审核通过吗？\',\'审核成功\')"></a>';
						if(row.status == 1) {
							return s + e + d;
						} else if(row.status == 0) {
							return s + e + o;
						}else if(row.status ==2) {
							return s + e + a;
						}
					}
				}
			]
		],
		function(data) {
			//设置按钮列easyUI样式
			setCell("修改", "解封", "停封", "查看");
			$('.tipcls').linkbutton({text:'',plain:false,iconCls:'icon-tip'});
			$('.tipcls').tooltip({    
				position: 'bottom',
				trackMouse:'true',
				content: '<span>审核通过</span>'    
			});
		}
	);
	var opt=$('#userGrid').datagrid('options');
	opt.singleSelect=false;
	opt.ctrlSelect=true;
	opt.onResize=function(width, height){
		var w=$("#main").width()-900;
		if (w<=0) {
			$("#uname").textbox({
				width:"100%"
			});
			$("#name").textbox({
				width:"100%"
			});
		} else {
			$("#uname").textbox({
				width:(w-80)/2
			});
			$("#name").textbox({
				width:(w-80)/2
			});
		}
	};
	var w=$("#main").width()-900;
	if (w<=0) {
		$("#uname").textbox({
			width:"100%"
		});
		$("#name").textbox({
			width:"100%"
		});
	} else {
		$("#uname").textbox({
			width:(w-80)/2
		});
		$("#name").textbox({
			width:(w-80)/2
		});
	}
});
function showUser(index) {
	$("#pwdtr").hide(0);
	$("#repwdtr").hide(0);
	$('#userGrid').datagrid('selectRow', index);
	var row = $('#userGrid').datagrid('getRows')[index];
	$('#fm').form('load', row);
	$("#dlg .easyui-textbox").textbox({    
		readonly:true
	});
	$("#dlg .easyui-combobox").textbox({    
		readonly:true
	});
	$("#dlg .easyui-datebox").textbox({    
		readonly:true
	});
	$('#dlg').dialog({
		title: '查看用户信息',
		height:205,
		iconCls: 'icon-search',
		buttons:null
	});
	if (row.provinceId>0) {
		$.each(provinces, function(index, value) {
			if (row.provinceId==value.id) {
				if (!value.cities) {
					$.ajax({
						url: PROJECT_NAME + '/city_list.do',
						type: 'POST',
						data:{provinceId:row.provinceId},
						dataType: "json",
						success: function(data, status) {
							value.cities=data;
							var cd=new Array();
							cd.push({ "text": "请选择","value": 0,"selected":true});
							$.each(value.cities,function(i,v){
								cd.push({ "text": v.name,"value": v.id});
							});
							$('#city').combobox('loadData',cd);
							$('#city').combobox('select',row.cityId);
						},
						err: function(XMLHttpRequest, textStatus, err) {
							$.messager.alert('错误', '对不起，获取城市列表失败！', 'error');
						}
					});
				}else{
					var cd=new Array();
					cd.push({ "text": "请选择","value": 0,"selected":true});
					$.each(value.cities,function(i,v){
						cd.push({ "text": v.name,"value": v.id});
					});
					$('#city').combobox('loadData',cd);
					$('#city').combobox('select',row.cityId);
				}
				
				return false;
			}
		});
	}else{
		$('#city').combobox('loadData',[{ "text": "请选择","value": 0,"selected":true}]);
	}
	$('#dlg').dialog('open');
	
}

function editUser(index) {
	$("#pwdtr").hide(0);
	$("#repwdtr").show(0);
	$("#repwd").textbox('clear');
	$('#userGrid').datagrid('selectRow', index);
	var row = $('#userGrid').datagrid('getRows')[index];
	$("#dlg .easyui-textbox").textbox({    
		readonly:false
	});
	$("#dlg .easyui-combobox").textbox({    
		readonly:false
	});
	$("#dlg .easyui-datebox").textbox({    
		readonly:false
	});
	$('#fm').form('load', row);
	$('#dlg').dialog({
		title: '修改用户信息',
		height:275,
		iconCls: 'icon-edit',
		buttons:[{
			text:'确定',
			iconCls: 'icon-ok',
			handler:function(){
				var repwd=$("#repwd").textbox('getValue');
				if (repwd) {
					$.messager.confirm('确认重置','您确认重置该帐号密码吗？',function(r){    
						if (r){
							$("#pwd").textbox('setValue',repwd);
						}
						submitForm({
				    		url:PROJECT_NAME + '/user_saveorupdate.do',
				    		msg:"修改成功",
				    		action:"update",
				    		reload:false,
				    		index:index,
				    		row:$('#fm').serializeJson()
				    	});
					}); 
				}else{
					submitForm({
			    		url:PROJECT_NAME + '/user_saveorupdate.do',
			    		msg:"修改成功",
			    		action:"update",
			    		reload:false,
			    		index:index,
			    		row:$('#fm').serializeJson()
			    	});
				}
			}
		},{
			text:'关闭',
			iconCls: 'icon-cancel',
			handler:function(){
				$('#dlg').dialog('close');
			}
		}]
	});
	
	if (row.provinceId>0) {
		$.each(provinces, function(index, value) {
			if (row.provinceId==value.id) {
				if (!value.cities) {
					$.ajax({
						url: PROJECT_NAME + '/city_list.do',
						type: 'POST',
						data:{provinceId:row.provinceId},
						dataType: "json",
						success: function(data, status) {
							value.cities=data;
							var cd=new Array();
							cd.push({ "text": "请选择","value": 0,"selected":true});
							$.each(value.cities,function(i,v){
								cd.push({ "text": v.name,"value": v.id});
							});
							$('#city').combobox('loadData',cd);
							$('#city').combobox('select',row.cityId);
						},
						err: function(XMLHttpRequest, textStatus, err) {
							$.messager.alert('错误', '对不起，获取城市列表失败！', 'error');
						}
					});
				}else{
					var cd=new Array();
					cd.push({ "text": "请选择","value": 0,"selected":true});
					$.each(value.cities,function(i,v){
						cd.push({ "text": v.name,"value": v.id});
					});
					$('#city').combobox('loadData',cd);
					$('#city').combobox('select',row.cityId);
				}
				
				return false;
			}
		});
	}else{
		$('#city').combobox('loadData',[{ "text": "请选择","value": 0,"selected":true}]);
	}
	$('#dlg').dialog('open');
}

function submitForm(paras){
	$('#fm').form('submit', {    
	    url:paras.url,
	    queryParams:{"action":paras.action},
	    onSubmit:function(para){
	    	 $.messager.progress({
                text: '请稍候...',
                interval: 500
            });
	    	var valid=$('#fm').form("validate");
	    	if (valid) {
	    		$.ajax({
	    			url: PROJECT_NAME + '/user_exist.do',
	    			type: 'POST',
	    			async:false,
	    			data:{
	    				userName:$("#dlguname").textbox('getValue'),
	    				userId:$("#userId").val()
	    			},
	    			dataType: "json",
	    			success: function(data, status) {
	    				if(data=="1"){
	    					valid=false;
	    					$.messager.progress('close');
	    					$.messager.alert('错误', '对不起，用户名已存在！', 'error');
	    				}
	    			},
	    			err: function(XMLHttpRequest, textStatus, err) {
	    				$.messager.progress('close');
	    				$.messager.alert('错误', '对不起，验证用户名失败！', 'error');
	    			}
	    		});
			}else{
				$.messager.progress('close');
			}
	    	
	    	 return valid;
	    },
	    success:function(data){
	    	$.messager.progress('close');
	        if(parseInt(data)>0){
	        	$('#dlg').dialog('close');
	        	showMsgBox(paras.msg);
	        	if (paras.reload) {
	        		$("#userGrid").datagrid('reload');
				}else{
					if (paras.append) {
						paras.row.id=parseInt(data);
						$('#userGrid').datagrid('appendRow',paras.row);
					} else {
						$('#userGrid').datagrid('updateRow',{
							index: paras.index,
							row: paras.row
						});
					}
					setCell("修改", "解封", "停封", "查看");
					$('.tipcls').linkbutton({text:'',plain:false,iconCls:'icon-tip'});
					$('.tipcls').tooltip({    
						position: 'bottom',
						trackMouse:'true',
						content: '<span>审核通过</span>'    
					});
				}
	        }else{
	        	$.messager.alert("错误", "操作失败！请与系统管理员联系!", 'error');
	        }
	    }    
	});
}

function lockUser(index) {
	$('#userGrid').datagrid('selectRow', index);
	var row = $('#userGrid').datagrid('getRows')[index];
	$('#fm').form('load', row);
	$.messager.confirm('确认封停','您确认封停该帐号吗？',function(r){    
	    if (r){
	    	$("#dlgstatus").val(0);
	    	row.status=0;
	    	submitForm({
	    		url:PROJECT_NAME + '/user_saveorupdate.do',
	    		msg:"封停成功",
	    		action:"update",
	    		reload:false,
	    		index:index,
	    		row:row
	    	});
	    }    
	}); 
}
function unlockUser(index,msg,tip) {
	$('#userGrid').datagrid('selectRow', index);
	var row = $('#userGrid').datagrid('getRows')[index];
	$('#fm').form('load', row);
	$.messager.confirm('确认操作',msg,function(r){    
	    if (r){    
	    	$("#dlgstatus").val(1);
	    	row.status=1;
	    	submitForm({
	    		url:PROJECT_NAME + '/user_saveorupdate.do',
	    		msg:tip,
	    		action:"update",
	    		reload:false,
	    		index:index,
	    		row:row
	    	});
	    }    
	}); 
}
function updateUsersStatus(msg,action){
	var sels=checkSelection();
	if (sels) {
	$.messager.confirm('确认操作','您确认批量'+msg+'吗？',function(r){    
		if (r){
				var ids=[];
				var oldStatus,newStatus;
				if (action=="active") {
					oldStatus=2;
					newStatus=1;
				}else if (action=="lock") {
					oldStatus=1;
					newStatus=0;
				}else if (action=="unlock") {
					oldStatus=0;
					newStatus=1;
				}
				$.each(sels, function(idx, value) {
						if (value.status==oldStatus) {
							ids.push(value.id);
							value.status=newStatus;
						}
				});
				if (ids.length>0) {
					$.messager.progress({
		                text: '请稍候...',
		                interval: 500
		            });
					$.ajax({
						url: PROJECT_NAME + '/user_updatestatus.do',
						data:{
							"ids":ids,
							"status":newStatus},
						type: 'POST',
						dataType: "json",
						success: function(data, status) {
							$.messager.progress('close');
							if (data=="1") {
								showMsgBox(msg+"成功");
							} else {
								showMsgBox(msg+"失败");
							}
							var rows=$('#userGrid').datagrid('getRows');
							for (var i = 0; i < rows.length; i++) {
								$('#userGrid').datagrid('refreshRow',i);
							}
							setCell("修改", "解封", "停封", "查看");
							$('.tipcls').linkbutton({text:'',plain:false,iconCls:'icon-tip'});
							$('.tipcls').tooltip({    
								position: 'bottom',
								trackMouse:'true',
								content: '<span>审核通过</span>'    
							});
						},
						err: function(XMLHttpRequest, textStatus, err) {
							$.messager.progress('close');
							$.messager.alert('错误', '对不起，批量操作失败！', 'error');
						}
					});
				} else {
					 $.messager.alert("警告", "没有需要"+msg+"的用户!", 'warning');
				}
			}
		});
	}
}
function checkSelection(){
	 var sels=$('#userGrid').datagrid('getSelections');
	 if (sels.length<=0) {
		 $.messager.alert("警告", "没有选择任何记录!", 'warning');
	} else {
		return sels;
	}
}

